package com.jerry.hm.datastructure.heap;

import java.util.Arrays;

/**
 * 大顶堆
 *
 * @author Jerry
 * @since 2024/10/7 20:44
 */
public class MaxHeap {

    private int[] array;
    private int size;

    public MaxHeap(int capacity) {
        array = new int[capacity];
    }

    public MaxHeap(int[] array) {
        this.array = array;
        this.size = array.length;
        heapify();
    }

    /**
     * 建堆：找到最后一个非叶子结点，从后向前，对每个节点执行下潜
     */
    private void heapify() {
        // 找到最后非叶子结点。（索引从0开始）size / 2 -1
        for (int i = size / 2 - 1; i >= 0; i--) {
            dive(i);
        }
    }

    /**
     * 获取堆顶元素
     *
     * @return
     */
    public int peek() {
        if (size == 0) {
            throw new RuntimeException("Heap is empty");
        }
        return array[0];
    }

    /**
     * 移除堆定元素
     *
     * @return
     */
    public int poll() {
        if (size == 0) {
            throw new RuntimeException("Heap is empty");
        }
        int top = array[0];
        // 堆顶和最后一个元素交换
        swap(0, size - 1);
        size--;
        // 堆顶元素下潜
        dive(0);
        return top;
    }

    /**
     * 移除指定索引的元素
     *
     * @param index
     * @return
     */
    public int poll(int index) {
        if (index > size - 1) {
            throw new IllegalArgumentException("Index out of bounds");
        }
        int target = array[index];
        // 堆顶和最后一个元素交换
        swap(index, size - 1);
        size--;
        // 堆顶元素下潜
        dive(index);
        return target;
    }

    /**
     * 替换堆顶元素
     *
     * @param replaced
     */
    public void replace(int replaced) {
        if (size == 0) {
            throw new RuntimeException("Heap is empty");
        }
        array[0] = replaced;
        dive(0);
    }

    /**
     * 堆的尾部添加元素
     *
     * @param offered
     * @return
     */
    public boolean offer(int offered) {
        if (size == array.length) {
            return false;
        }
        up(offered);
        size++;
        return true;
    }

    @Override
    public String toString() {
        return "MaxHeap{" +
                "array=" + Arrays.toString(array) +
                '}';
    }

    /**
     * 下潜元素
     *
     * @param parent
     */
    private void dive(int parent) {
        int left = parent * 2 + 1;
        int right = left + 1;
        int max = parent;
        if (left < size && array[left] > array[max]) {
            max = left;
        }
        if (right < size && array[right] > array[max]) {
            max = right;
        }
        if (max != parent) {
            swap(max, parent);
            dive(max);
        }
    }

    /**
     * 交换两个元素
     *
     * @param i
     * @param j
     */
    private void swap(int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    /**
     * 上浮
     *
     * @param offered
     */
    private void up(int offered) {
        int child = size;
        while (child > 0) {
            int parent = (child - 1) / 2;
            if (offered > array[parent]) {
                array[child] = array[parent];
            } else {
                break;
            }
            child = parent;
        }
        array[child] = offered;
    }
}
